$(document).ready(function() {
	var login = function () {
		// Get username and password
		var username = $.trim($('input[name=username').val()),
			password = hex_md5($.trim($('input[name=password').val())),		// Encrypt password
			$form    = $('.ui.form');
	
		// Change form on loading state
		$form.addClass('loading');
	
		$.myAjax(
			_CTX_PATH_ + '/login', 
			{
				username : username,
				password : password
			}, function(data) {
				// Remove loading state
				$form.removeClass('loading');
				if (data.result == true) {
					window.location.href = data.url;
				} else {
					var errors = new Array();
					errors[0] = '用户名密码不匹配';
					$('.ui.form').form('add errors', errors).addClass('error');
				}
			}
		);
	};
	
	$('.ui.form').form({
		username: {
			identifier: 'username',
			rules: [
				{
					type: 'empty',
					prompt: '用户名不能为空'
				},
				{
					type: 'length[5]',
					prompt: '用户名长度至少为5位'
				}
			]
		},
		password: {
			identifier: 'password',
			rules: [
				{
					type: 'empty',
					prompt: '密码不能为空'
				},
				{
					type: 'length[5]',
					prompt: '密码长度至少为5位'
				}
			]
		}
	}, {
		onSuccess : login
	});			
});